﻿using System.Globalization;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.TaskRob;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace H2.NET.Web.Pages.SMD
{
    public partial class DiscardDevice : BasePage
    {
        private int _storeid;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btn_submit.Visible = TaskAPI.IsAllowSubmit;
                if (ReadOnly()) return;

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    JsTip(string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser));
                    return;
                }

                #region 数据加载显示

                _storeid = TaskAPI.GetStoreId("storeid");

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                DwzAssessment1.Category = "DiscardDevice";

                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);

                switch (TaskAPI.Step)
                {
                    case "Submit Data":
                        {
                            var devices = DeviceService.FindNormalDevice(_storeid);
                            ddl_devices.AppendDataBoundItems = true;
                            ddl_devices.DataSource = devices;
                            ddl_devices.DataTextField = "FullSetSN";
                            ddl_devices.DataValueField = "DeviceID";
                            ddl_devices.DataBind();

                            uc_store_info1.IsCanEditAuthID = _storeid > 0;
                            uc_store_info1.store = StoreService.GetSmdStoreById(_storeid);
                            if (devices == null || devices.Count == 0)
                            {
                                btn_submit.Visible = false;
                            }
                            else
                            {
                                // 默认选中第一个
                                InitDeviceOption(devices[0].Status);
                                ddl_devices.SelectedIndex = 0;
                                btn_submit.Visible = true;
                            }

                            if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                            {
                                assessment.Visible = true;
                                var deviceid = TaskAPI.GetVariableBySingleValue("DeviceID");
                                var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(deviceid, 0));
                                var store = StoreService.GetSmdStoreById(_storeid);
                                var changelogs = ChangeLogService.GetLastChangeLogs(assIds);

                                InitDeviceOption(device.Status);

                                device = DataHelper<t_smd_Device>.Reload(device, changelogs);

                                uc_store_info1.store = store;
                                ddl_devices.SelectedValue = device.FullSetSN;
                                var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                                cb_DepositConfiscated.Checked = storeMasterData.ShakerModel == "True";
                            }
                        }
                        break;
                    case "Manager Approve":
                    case "Data Check":
                        {
                            var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                            if (storeMasterData == null)
                            {
                                JsTip("加载数据失败，请关闭页面重新打开！");
                                return;
                            }

                            hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                            hl_ExportPdf.Visible = true;
                            uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                            var deviceid = TaskAPI.GetVariableBySingleValue("DeviceID");
                            var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(deviceid, 0));
                            var store = StoreService.GetSmdStoreById(_storeid);
                            var changelogs = ChangeLogService.GetLastChangeLogs(assIds);

                            InitDeviceOption(device.Status);

                            device = DataHelper<t_smd_Device>.Reload(device, changelogs);

                            uc_store_info1.store = store;
                            uc_store_info1.IsCanEditAuthID = false;
                            assessment.Visible = true;
                            rbl_status.SelectedValue = device.Status;
                            ddl_devices.Visible = false;
                            l_devices.Text = device.FullSetSN;
                            cb_DepositConfiscated.Checked = storeMasterData.ShakerModel == "True";
                        }
                        break;
                    default:
                        {
                            var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                            if (storeMasterData == null)
                            {
                                btn_submit.Visible = false;
                                JsTip("加载数据失败，请关闭页面重新打开！");
                                return;
                            }
                            hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                            hl_ExportPdf.Visible = true;
                            uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                            var deviceid = TaskAPI.GetVariableBySingleValue("DeviceID");

                            var store = StoreService.GetSmdStoreById(_storeid);
                            var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(deviceid, 0));
                            var changelogs = ChangeLogService.GetLastChangeLogs(assIds);

                            var devices = new List<v_DeviceDeposit>();
                            devices.Add(DeviceService.GetDeviceDepositById(Utils.StrToInt(deviceid, 0)));

                            device = DataHelper<t_smd_Device>.Reload(device, changelogs);

                            uc_store_info1.store = store;
                            uc_store_info1.IsCanEditAuthID = false;
                            assessment.Visible = true;
                            rbl_status.Visible = false;
                            l_status.Text = device.Status;
                            ddl_devices.Visible = false;
                            l_devices.Text = device.FullSetSN;

                            cb_DepositConfiscated.Visible = false;
                            cb_DepositConfiscated.Checked = storeMasterData.ShakerModel == "True";
                            l_DepositConfiscated.Text = storeMasterData.ShakerModel == "True" ? "是" : "否";
                        }
                        break;
                }

                #endregion
            }
        }

        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                assessment.Visible = true;
                btn_submit.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;

                var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                if (storeMasterData == null)
                {
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                var ass = AssessmentService.GetBySubmitData(TaskAPI.Process, TaskAPI.Incident);
                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
                var store = StoreService.GetSmdStoreById(storeMasterData.StoreId.Value);
                var device = DeviceService.GetSmdDeviceById(storeMasterData.DeviceId.Value);
                var changelogs = ChangeLogService.GetLastChangeLogs(assIds);

                var devices = new List<v_DeviceDeposit>();
                devices.Add(DeviceService.GetDeviceDepositById(storeMasterData.DeviceId.Value));
                DataHelper<t_smd_Device>.Reload(device, changelogs);

                uc_store_info1.IsCanEditAuthID = false;
                assessment.Visible = true;
                rbl_status.Visible = false;
                ddl_devices.Visible = false;
                cb_DepositConfiscated.Visible = false;

                uc_store_info1.store = store;
                l_status.Text = device.Status;
                l_devices.Text = device.FullSetSN;
                l_DepositConfiscated.Text = storeMasterData.ShakerModel == "True" ? "是" : "否";

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }

            return false;
        }
        #endregion

        private bool Send(ref string returnMsg)
        {
            var _store = uc_store_info1.store;
            var _dealer = DealerService.GetById(_store.DealerID.Value);
            var _summary = "|" + _store.AuthID + "|" + _dealer.DealerCode + "|" + _store.StoreType;
            bool flag;
            try
            {
                _storeid = TaskAPI.GetStoreId("storeid");

                #region 数据验证
                if (TaskAPI.Step == "Submit Data" && TaskAPI.IsAllowSubmit) // 如果是退回的情况，不存在验证
                {
                    if (_storeid == 0)
                    {
                        returnMsg = "请选择门店";
                        return false;
                    }
                    var deviceid = Utils.StrToInt(ddl_devices.SelectedValue, 0);
                    if (deviceid == 0)
                    {
                        returnMsg = "请选择设备";
                        return false;
                    }

                    var devices = new List<int>();
                    devices.Add(deviceid);

                    if (DeviceService.IsUnfinish(devices) && !TaskAPI.Summary.Contains("退回"))
                    {
                        returnMsg = "发现有设备其他业务流程中，请先完成其他流程。";
                        return false;
                    }

                    if (string.IsNullOrEmpty(rbl_status.SelectedValue))
                    {
                        returnMsg = "请选择设备状态";
                        return false;
                    }

                    var deposit = (t_smd_Deposit._DepositType == "设备保证金" & t_smd_Deposit._DeviceID == ddl_devices.SelectedValue).ListFirst<t_smd_Deposit>(Storage.Context3, "DepositId desc");
                    if (deposit != null && deposit.Amount > 0 && !cb_DepositConfiscated.Checked && rbl_status.SelectedValue != "经销商处寄存")
                    {
                        returnMsg = "若有设备保证金，请勾选需发起保证金变更流程！";
                        return false;
                    }

                    if ((deposit == null || deposit.Amount == 0) && cb_DepositConfiscated.Checked)
                    {
                        returnMsg = "此设备没有保证金或保证金为0,不需要发起保证金变更！";
                        return false;
                    }

                }


                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        returnMsg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        returnMsg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }
                }
                #endregion

                #region 引擎传值
                if (TaskAPI.Step == "Submit Data")
                {
                    TaskAPI["BlankVlue"] = _storeid;
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    TaskAPI["DeviceID"] = ddl_devices.SelectedValue;
                    var deivce = DeviceService.GetSmdDeviceById(Utils.StrToInt(ddl_devices.SelectedValue, 0));
                    var store = StoreService.GetSmdStoreById(deivce.StoreID ?? 0);
                    TaskAPI.Summary = "设备报废or库存区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "-" + deivce.FullSetSN + "-" + store.StoreName + _summary;
                }
                else
                {
                    TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    var deivce = DeviceService.GetSmdDeviceById(Utils.StrToInt(TaskAPI.GetVariableBySingleValue("DeviceID"), 0));
                    switch (TaskAPI.Step)
                    {
                        case "Data Check":
                            TaskAPI["Checked"] = DwzAssessment1.Assessment.Opinion;
                            if (DwzAssessment1.Assessment.Opinion == "1")
                                TaskAPI.Summary = "设备报废or库存CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + deivce.FullSetSN + _summary;
                            else
                                TaskAPI.Summary = "(退回)登记设备报废or库存/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + deivce.FullSetSN + _summary;
                            break;
                        case "Manager Approve":
                            TaskAPI["Approved"] = DwzAssessment1.Assessment.Opinion;
                            if (DwzAssessment1.Assessment.Opinion == "1")
                                TaskAPI.Summary = "DMO导入核查/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + deivce.FullSetSN + _summary;
                            else
                                TaskAPI.Summary = "(退回)设备报废or库存区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + deivce.FullSetSN + _summary;
                            break;
                        case "DMO Commit":
                            TaskAPI["Commited"] = DwzAssessment1.Assessment.Opinion;
                            if (DwzAssessment1.Assessment.Opinion == "0")
                                TaskAPI.Summary = "(退回)设备报废or库存CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + "|" + deivce.FullSetSN + _summary;
                            break;
                    }
                }

                #endregion

                #region 提交步骤
                var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                var step = string.Empty;
                Storage.TransactionExecute(o =>
                {
                    #region 业务流程、审批意见记录

                    var ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }


                    #endregion

                    #region “Submit Data”步骤
                    if (TaskAPI.Step == "Submit Data")
                    {
                        var storeMasterData = new t_StoreMasterData
                        {
                            SubmitDate = DateTime.Now,
                            Creator = TaskAPI.UserName,
                            ApplicationNO = uc_head1.applicationNo,
                            Process = TaskAPI.Process,
                            Incident = TaskAPI.Incident,
                            StoreId = _storeid,
                            DeviceId = Utils.StrToInt(ddl_devices.SelectedValue, 0),

                            // 是否涉及保证金罚没
                            ShakerModel = cb_DepositConfiscated.Checked.ToString(),
                            BusinessProcess = ass.BusinessProcess,
                            BusinessKey = ass.BusinessKey

                        };
                        Storage.Save(Storage.Context1, storeMasterData);

                        // 记录变更日志
                        var changelogs = SaveChangeLog(Utils.StrToInt(ddl_devices.SelectedValue, 0), ass.ID);
                        Storage.Save(Storage.Context1, changelogs.ToArray());
                        BusinessService.SaveChildProcess(TaskAPI, ass, "active");
                        var store = StoreService.GetSmdStoreById(_storeid);
                        var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(ddl_devices.SelectedValue, 0));
                        var dealer = DealerService.GetById(store.DealerID.Value);
                        BusinessService.saveProcessRelation(TaskAPI, ass, store, device, dealer, null, null, null, null);

                        if (!TaskAPI.Summary.Contains("退回"))
                        {
                            TaskAPI.Summary = "设备报废or库存区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + "-" + ass.BusinessKey + _summary;
                        }

                    }
                    #endregion

                    #region “Data Check”，“Manager Approve”步骤
                    else if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                    {
                        var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                        storeMasterData.ShakerModel = cb_DepositConfiscated.Checked.ToString();
                        Storage.Save(Storage.Context1, storeMasterData);

                        // 记录变更日志
                        var changelogs = SaveChangeLog(storeMasterData.DeviceId.Value, ass.ID);
                        Storage.Save(Storage.Context1, changelogs.ToArray());
                    }
                    #endregion

                    #region “DMO Commit”步骤
                    else if (TaskAPI.Step == "DMO Commit")
                    {
                        if (DwzAssessment1.Assessment.Opinion != "1") return;

                        // 将变更日志转移至smd数据库
                        var smdChangelogs = ChangeLogService.McdToSmd(AssessmentService.GetIdsByTaskApi(TaskAPI));
                        Storage.Save(Storage.Context3, smdChangelogs.ToArray());

                        // 获取业务数据主键
                        var id = smdChangelogs[0].DataID;
                        // 获取原始门店数据
                        var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(id, 0));
                        // 根据变更日志重新加载门店信息
                        device = DataHelper<t_smd_Device>.Reload(device, smdChangelogs);
                        // 更新门店信息
                        Storage.Save(Storage.Context3, device);

                        // 更新业务数据状态
                        StoreMasterDataService.UpdateFinish(TaskAPI);

                        step = "Finish";
                        BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                        //保存bussinesskey2017/9/20
                        var masterStore = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                        BusinessService.SaveSycnMappingAndBusinesskey(3, masterStore.BusinessKey); 
                    }
                    #endregion
                });

                // 变更列表
                TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                if (rbl_status.SelectedValue == "报废")
                {
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        TaskAPI["Alert"] = "以下设备已经系统完成报废更新，并获得CSM审批。";
                    }
                    else
                    {
                        TaskAPI["Alert"] = "以上设备已经完成报废，请确认各类审批及照片完整。同时确保对应设备在Tinting中已经删除。";
                    }
                }
                flag = TaskAPI.Send();

                //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.Step == "Submit Data")
                {
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                }
                #endregion
                else if (step == "Finish")
                {
                    BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                    if (!string.IsNullOrEmpty(key) && key == Constant.PROCESS_CHANGESTATUS)
                    {
                        var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                        if (storeMasterData == null) Logging.GetLogger().Error("调用DiscardDevice.aspx方法storeMasterData出错：storeMasterData对象为空！");
                        var chooseDevice = DeviceService.GetSmdDeviceById(Utils.StrToInt(TaskAPI.GetVariableBySingleValue("DeviceID"), 0));
                        if (chooseDevice == null) Logging.GetLogger().Error("调用DiscardDevice.aspx方法storeMasterData出错：chooseDevice对象为空！");
                        var device = DeviceService.GetSmdDeviceById(storeMasterData.DeviceId.Value);
                        // 判断设备是否报废
                        // 新增一条设备终止合同
                        if (device.Status.Trim() != "经销商处寄存")
                        {
                            if (chooseDevice != null)
                            {
                                var deviceContractCancel = ContractDeviceService.GetContractDeviceCancel(ContractDeviceService.getContractDeviceByDeviceId(chooseDevice.DeviceID) ?? new t_smd_ContractDevice { DeviceID = chooseDevice.DeviceID, DeviceFixAssetNo = device.FullSetSN });
                                var deviceContractOld = ContractDeviceService.GetOldContractDevice(ContractDeviceService.getContractDeviceByDeviceId(chooseDevice.DeviceID) ?? new t_smd_ContractDevice { DeviceID = chooseDevice.DeviceID, DeviceFixAssetNo = device.FullSetSN });
                                if (deviceContractOld == null)
                                    Logging.GetLogger().Error("调用DiscardDevice.aspx方法storeMasterData出错：deviceContractOld对象为空！");
                                deviceContractOld.DeviceCancelContractType =
                                    ContractDeviceService.getContractDeviceByDeviceId(chooseDevice.DeviceID) == null ? "" : ContractDeviceService.getContractDeviceByDeviceId(chooseDevice.DeviceID).DeviceContractType;
                                Storage.Save(Storage.Context3, deviceContractOld);
                                Storage.Save(Storage.Context3, deviceContractCancel);
                                (t_smd_ContractDevice._DeviceID == chooseDevice.DeviceID).Delete<t_smd_ContractDevice>(Storage.Context3);
                            }
                            #region 发起合同变更流程


                            var taskAPI = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                            var applicationNo = GenerateApplicationNo(taskAPI);

                            taskAPI["ParentProcess"] = TaskAPI.Process;
                            taskAPI["ParentIncident"] = TaskAPI.Incident;
                            taskAPI["AutoBusinessKey"] = key;
                            taskAPI["BlankVlue"] = TaskAPI.GetStoreId("storeid");
                            taskAPI["DeviceID"] = TaskAPI.GetVariableBySingleValue("DeviceID");
                            taskAPI["Actions"] = "ChangeContract";
                            taskAPI["Alert"] = "此门店需要进行签署以下合同，请通知相关人员签署合同并提交总部 （可进入系统批量处理）：\n\r合同终止及三方转移合同";
                            taskAPI.InitAutoTask(applicationNo);
                            taskAPI.Summary = "提交合同信息变更/" + TaskHelper.getSummary(TaskAPI.Summary);

                            var store = StoreService.GetSmdStoreById(storeMasterData.StoreId.Value);
                           
                            taskAPI["MailSubject"] = string.Format("固定资产号：{0}--授权号：{1} -- {2}）", device.FullSetSN, store.AuthID, store.StoreType);

                            taskAPI.SetStoreDataChangeRecipient(
                                TaskAPI.GetVariableBySingleValue("Region"),
                                TaskAPI.GetVariableBySingleValue("Province"),
                                "Contract");

                            if (taskAPI.Send())
                            {
                                var ass = taskAPI.InitAutoAssessment();

                                Storage.Save(Storage.Context1, ass);

                                BusinessService.SaveChildProcess(taskAPI, ass, "active");
                            }

                            #endregion

                            if (storeMasterData.ShakerModel == "True")
                            {
                                //Logging.GetLogger().Error("1-2:保证金变更流程");
                                #region 自动发起保证金变更

                                var region = TaskAPI.GetVariableBySingleValue("Region").ToUpper();
                                var province = TaskAPI.GetVariableBySingleValue("Province");

                                taskAPI = new TaskAPI(TaskHelper.STORE_DEPOSIT_CHANGE_TASKID);
                                applicationNo = GenerateApplicationNo(taskAPI);

                                taskAPI["ParentProcess"] = TaskAPI.Process;
                                taskAPI["ParentIncident"] = TaskAPI.Incident;
                                taskAPI["AutoBusinessKey"] = key;
                                taskAPI["BlankVlue"] = TaskAPI.GetStoreId("storeid");
                                taskAPI["DeviceID"] = TaskAPI.GetVariableBySingleValue("DeviceID");
                                taskAPI["Region"] = region;
                                taskAPI["Province"] = province;
                                taskAPI.InitAutoTask(applicationNo);
                                taskAPI.Summary = "设备保证金变更/" + TaskHelper.getSummary(TaskAPI.Summary);
                                taskAPI.SetDepositChangeRecipient(region, province);

                                if (taskAPI.Send())
                                {
                                    var ass = taskAPI.InitAutoAssessment();

                                    Storage.Save(Storage.Context1, ass);

                                    BusinessService.SaveChildProcess(taskAPI, ass, "active");
                                }

                                #endregion
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                returnMsg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用DiscardDevice.aspx方法Send_Click出错：" + ex);
                flag = false;
            }
            return flag;
        }

        #region 绑定各选项
        private void InitDeviceOption(string status)
        {
            rbl_status.Items.Clear();

            var configService = new ConfigService();
            if (status == "公司大仓")
            {
                var statuses = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBZT') and (code = 'Device_BF' or code = 'Device_JC') order by Seq").Tables[0];
                foreach (DataRow row in statuses.Rows)
                {
                    rbl_status.Items.Add(new ListItem(row["name"].ToString(), row["value"].ToString()));
                }
            }
            else if (status == "经销商处寄存")
            {
                var statuses = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBZT') and (code = 'Device_BF' or code = 'Device_KC') order by Seq").Tables[0];
                foreach (DataRow row in statuses.Rows)
                {
                    rbl_status.Items.Add(new ListItem(row["name"].ToString(), row["value"].ToString()));
                }
            }
            else
            {
                var statuses = configService.GetList("ParentId = (select configid from t_smd_Config where code='S_SBZT') and code != 'Device_NO' and code != 'Device_YX' order by Seq").Tables[0];
                foreach (DataRow row in statuses.Rows)
                {
                    rbl_status.Items.Add(new ListItem(row["name"].ToString(), row["value"].ToString()));
                }
            }
        }
        #endregion

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            var returnMsg = string.Empty;
            if (Send(ref returnMsg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
            }
            else
            {
                returnMsg = string.IsNullOrEmpty(returnMsg) ? Resources.Global.C_00_Failed : returnMsg;
                ScriptManager.RegisterStartupScript(this, GetType(), "info_tip", "$.jBox.prompt('" + returnMsg + "','提示', 'info');", true);
            }
        }

        private List<t_StoreDataChangeLog> SaveChangeLog(int deviceid, string assid)
        {
            var existing_changelogs = ChangeLogService.GetLastChangeLogs(TaskAPI);

            var device = DeviceService.GetSmdDeviceById(deviceid);
            var newDevice = (t_smd_Device)device.CloneObject();
            DataHelper<t_smd_Device>.Reload(device, existing_changelogs);

            newDevice.Status = rbl_status.SelectedValue;

            var changelogs = DataHelper<t_smd_Device>.GetChangeLogs(device, newDevice,
                newDevice.GetChangeFields(), "DeviceID", UserAPI.UserFullName, assid, "DiscardDevice");

            return ChangeLogService.GetDistinctChangeLogs(changelogs, existing_changelogs);
        }

        protected void ddl_devices_SelectedIndexChanged(object sender, EventArgs e)
        {
            var deviceId = Utils.StrToInt(ddl_devices.SelectedValue, 0);
            var device = DeviceService.GetSmdDeviceById(deviceId);

            InitDeviceOption(device.Status);
        }

    }
}